package org.jef.auth.support.wechat;

import org.jef.auth.support.base.OAuth2ResourceOwnerBaseAuthenticationConverter;
import org.jef.core.constant.SecurityConstants;
import org.jef.security.util.OAuth2EndpointUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Set;

/**
 * @version 1.0
 * @program: OAuth2ResourceOwnerWechatAuthenticationConverter
 * @description: 微信登录转换器
 * @author: ChengZhi 0336
 * @create: 2024-08-05 17:45
 **/
public class OAuth2ResourceOwnerWechatAuthenticationConverter extends OAuth2ResourceOwnerBaseAuthenticationConverter<OAuth2ResourceOwnerWechatAuthenticationToken> {

	/**
	 * 是否支持此convert
	 *
	 * @param grantType 授权类型
	 * @return
	 */
	@Override
	public boolean support(String grantType) {
		return SecurityConstants.WECHAT.equals(grantType);
	}

	@Override
	public OAuth2ResourceOwnerWechatAuthenticationToken buildToken(Authentication clientPrincipal, Set requestedScopes,
																   Map additionalParameters) {
		return new OAuth2ResourceOwnerWechatAuthenticationToken(new AuthorizationGrantType(SecurityConstants.WECHAT),
				clientPrincipal, requestedScopes, additionalParameters);
	}

	/**
	 * 校验扩展参数 密码模式密码必须不为空
	 *
	 * @param request 参数列表
	 */
	@Override
	public void checkParams(HttpServletRequest request) {
		MultiValueMap<String, String> parameters = OAuth2EndpointUtils.getParameters(request);

		String jsCode = parameters.getFirst(SecurityConstants.WECHAT_PARAMETER_JSCODE);
		if (!StringUtils.hasText(jsCode) || parameters.get(SecurityConstants.WECHAT_PARAMETER_JSCODE).size() != 1) {
			OAuth2EndpointUtils.throwError(OAuth2ErrorCodes.INVALID_REQUEST, SecurityConstants.WECHAT_PARAMETER_JSCODE,
					OAuth2EndpointUtils.ACCESS_TOKEN_REQUEST_ERROR_URI);
		}
	}
}

